import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'options.dart';

BaseOptions options = BaseOptions(
  baseUrl: BASEURL,
  headers: {
    "Authorization": TOKEN,
  },
);

class CustomInterceptors extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    print('REQUEST[${options.method}] => PATH: ${options.path}');
    EasyLoading.show(status: 'loading...');
    return super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    print(
        'RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
    EasyLoading.dismiss();
    return super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    print(
        'ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
    EasyLoading.dismiss();
    return super.onError(err, handler);
  }
}

class Request {
  static Dio _dio = Dio(options);
  static Future<T> _request<T>(String path,
      {String? method, Map<String, dynamic>? params, data}) async {
    _dio.interceptors.add(CustomInterceptors());
    try {
      Response response = await _dio.request(path,
          queryParameters: params,
          data: data,
          options: Options(method: method));
      return response.data;
    } on DioError catch (e) {
      return Future.error(e);
    }
  }

  static Future<T> get<T>(String path, {Map<String, dynamic>? params}) {
    return _request(path, method: 'get', params: params);
  }

  static Future<T> post<T>(String path, {Map<String, dynamic>? params, data}) {
    return _request(path, method: 'post', params: params, data: data);
  }
}
